package com.example.demo.signin.service.impl;

import com.example.demo.signin.service.ISignInService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname SignInServiceImpl
 * @description
 * @date 2023/07/11 9:35
 * <p>
 * ******************************************************
 */
@Service
public class SignInServiceImpl implements ISignInService {

    private final Logger logger = LoggerFactory.getLogger(SignInServiceImpl.class);

    private final String USER_SIGN_KEY= "sign:";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public Boolean sign(Long userId, Integer day) {
        //1. 获取登录用户
        //2. 获取日期
        LocalDateTime now = LocalDateTime.now();
        //3. 拼接key
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = USER_SIGN_KEY + userId + keySuffix;
        logger.info("redis key========" + key);
        //4. 获取今天是本月的第几天
        int dayOfMonth = now.getDayOfMonth();
        //5. 写入redis setbit key offset 1
        redisTemplate.opsForValue().setBit(key, dayOfMonth -1, true);
        return true;
    }

    @Override
    public String signCount(Long userId) {
        //1. 获取登录用户
        //2. 获取日期
        LocalDateTime now = LocalDateTime.now();
        //3. 拼接key
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = USER_SIGN_KEY + userId + keySuffix;
        //4. 获取今天是本月的第几天
        int dayOfMonth = now.getDayOfMonth();

        //5. 统计本月截止今天为止的打卡天数
        Long num = redisTemplate.execute((RedisCallback<Long>) con -> con.bitCount(key.getBytes(), 0, dayOfMonth));
        if (num == null || num == 0) {
            return "没有任务签到结果";
        }
        return String.valueOf(num);
    }


    /**
     * 统计本月截止今天为止的打卡天数
     * @param key
     * @param end
     * @return
     */
    private Long bitCount(String key, int end) {
        return redisTemplate.execute((RedisCallback<Long>) con -> con.bitCount(key.getBytes(), 0, end));
    }

}
